package com.ntty.client;

import hyl.core.MyDate;
import hyl.core.run.MyRun;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 心跳
 * 
 * @author Administrator
 *
 */
public class MyHeartHandler extends SimpleChannelInboundHandler<Object> {
	private ChannelHandlerContext ctx;
	private boolean isConnect = false;


	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		//Log.v("WZ", "连接正常channelActive");
		isConnect = true;
		if (this.ctx == null) {
			synchronized (MyHeartHandler.class) {
				if (this.ctx == null) {
					this.ctx = ctx;
					MyAppHeart();
				}
			}
		}
	}

	private void MyAppHeart() {
		MyRun.start用户线程(() -> {
			while (ctx != null && isConnect) {
				String data = "123";
				byte[] bytes = data.getBytes();
				if (isConnect) {
					ctx.writeAndFlush(Unpooled.buffer(bytes.length).writeBytes(bytes));
					MyDate.sleep(3000);
				}
			}
		});
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// EventLoop loop = ctx.channel().eventLoop();
		// loop.schedule(() -> SocketTcp.getInstance().connect(), 5, TimeUnit.SECONDS);
		super.channelInactive(ctx);
		// Log.v("WZ", "重新连接socket服务器");
		isConnect = false;
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		super.userEventTriggered(ctx, evt);
		// Log.v("WZ", "发送数据包");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		super.exceptionCaught(ctx, cause);
		// Log.v("WZ", "连接出现异常");
		this.ctx.close();
		this.ctx = null;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		// TODO Auto-generated method stub
	////Log.v("WZ", "连接正常messageReceived");
			ByteBuf msg1 = (ByteBuf) msg;
			byte[] bytes = new byte[msg1.readableBytes()];
			msg1.readBytes(bytes);
			String s = new String(bytes, "UTF-8");
			//Log.v("WZ", "接收到的消息:" + s);
	}
}
